package com.pdstudio.weather;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import pl.droidsonroids.gif.GifImageView;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;

import com.pdstudio.apapter.WarningAdapter;
import com.pdstudio.app.Application;
import com.pdstudio.bean.Warning;
import com.pdstudio.bean.WeatherActual;
import com.pdstudio.bean.WeatherDay;
import com.pdstudio.bean.WeatherProfile;
import com.pdstudio.bean.WeatherStamp;
import com.pdstudio.http.WeatherHttpMethod;
import com.pdstudio.util.Lunar;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.util.TimeUtil;
import com.pdstudio.util.UpdateManager;
import com.pdstudio.view.HorizontalListView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ForecastActivity extends Activity implements
		Application.EventHandler {

	private final int WhatIsGetWarnings = 4;

	private TextView currentTime;
	private ImageView imgWarning;// 预警图标
	private ListView dayWeathers;// 天气列表
	private HorizontalListView hourWeathers;// 小时预报
	private GridView gvWarnings;// 预警列表
	private SimpleAdapter daySimpleAdapter;
	private SimpleAdapter hourSimpleAdapter;
	private WarningAdapter warningAdapter;
	private ImageView tShareBtn;
	private ImageView tBroadCastBtn;
	// private TextToSpeech tts;// 朗读
	private WeatherProfile weatherProfile;

	// 语音合成对象
	private SpeechSynthesizer mTts;
	private static final String APPID = "=547f29d4";
	// 默认发音人
	private String voicer = "xiaoyan";

	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;

	private TextView tvDate;
	private TextView tvStatus;
	private TextView tvTemp;
	private TextView tvWindDirection;
	private TextView tvWind;

	private Handler handler = null;

	private UpdateManager mUpdateManager;

	private SharePreferenceUtil mSpUtil;
	private Application mApplication;

	private TextView tvActualTemp;
	private TextView tvActualAddress;
	private TextView tvActualTime;
	private TextView tvActualWet;
	private TextView tvActualFall;
	private TextView tvActualWindDirection;
	private TextView tvActualWind;

	private GifImageView ivNv;

	private List<Warning> warnings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forecast);

		// handler与线程之间的通信及数据处理
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					try {
						Toast.makeText(getApplicationContext(), "加载天气数据中", 0)
								.show();
						// msg.obj是获取handler发送信息传来的数据
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

						if (msg != null && msg.obj != null) {
							weatherProfile = (WeatherProfile) msg.obj;

							for (WeatherStamp o : weatherProfile.hourWeathers) {
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("hour", o.getHour());
								map.put("drawable", R.drawable.ww4);
								map.put("temp", o.getTemp());
								list.add(map);
							}
						}
						// 给ListView绑定数据
						setHourWeathers(list);
						setForecast(weatherProfile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (msg.obj != null && msg.what == 1) {
					try {
						String scode = (String) msg.obj;
						if (scode != null && !scode.equals("")) {
							int code = Integer.parseInt(scode);
							// 这里来检测版本是否需要更新
							mUpdateManager = new UpdateManager(
									ForecastActivity.this);
							mUpdateManager.checkUpdateInfo(code);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (msg.obj != null && msg.what == 2) {// 获取实况信息
					try {
						WeatherActual actual = (WeatherActual) msg.obj;
						if (actual == null) {
							Toast.makeText(getApplicationContext(),
									"对不起，当前城市没有数据！", 0).show();
							actual = new WeatherActual();
						}
						setActual(actual);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (msg.what == 3 && msg.obj != null) {// 天气列表
					@SuppressWarnings("unchecked")
					List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

					if (msg != null && msg.obj != null) {
						// weatherProfile = (WeatherProfile) msg.obj;

						for (WeatherDay o : (List<WeatherDay>) msg.obj) {
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("week", o.week);
							map.put("date", o.date);
							map.put("img", GetWeatherIcon(o.weatherStatus));
							map.put("high", o.highTemp);
							map.put("low", o.lowTemp);
							list.add(map);
						}
					}
					setDayWeathers(list);
				} else if (msg.what == WhatIsGetWarnings) {// 预警信息列表
					setWarnings(warnings);
				}
			}

		};

		Application.mListeners.add(this);
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		// 获取用户授权preference对象
		if (mSpUtil.getAuthCode().equals("")) {
			Intent intent = new Intent(this, UserAuthActivity.class);
			startActivity(intent);
		}

		// 初始化合成对象
		// 检测是否安装了讯飞语音服务
		try {
			// 初始化合成对象
			SpeechUtility.createUtility(this, SpeechConstant.APPID+APPID);
			mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
			//mEngineType = SpeechConstant.TYPE_LOCAL;
			/**
			 * 选择本地合成 判断是否安装语音+,未安装则跳转到提示安装页面
			 */
			if (!SpeechUtility.getUtility().checkServiceInstalled()) {
				IntallXunFei();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		ivNv = (GifImageView) findViewById(R.id.fore_nv);
		gvWarnings = (GridView) findViewById(R.id.warnings);

		setWeatherActual();
		setWeatherForecast();
		getWeatherActualData();// 获取天气实况信息
		setCurrentTime();// 设置日期农历
		setWarning();// 设置预警信息
		getDayWeathersData();// 天气预报列表
		setHourWeathers();// 小时预报列表
		setShareButtuon();
		setBroadcastButton();
		checkVersion();
	}

	@Override
	protected void onResume() {
		super.onResume();
		setContentView(R.layout.activity_forecast);

		// 获取用户授权preference对象
		if (mSpUtil.getAuthCode().equals("")) {
			Intent intent = new Intent(this, UserAuthActivity.class);
			startActivity(intent);
		}

		ivNv = (GifImageView) findViewById(R.id.fore_nv);
		gvWarnings = (GridView) findViewById(R.id.warnings);

		setWeatherActual();
		setWeatherForecast();
		getWeatherActualData();// 获取天气实况信息
		setCurrentTime();// 设置日期农历
		setWarning();// 设置预警信息
		getDayWeathersData();// 天气预报列表
		setHourWeathers();// 小时预报列表
		setShareButtuon();
		setBroadcastButton();
	}

	private void setBroadcastButton() {
		tBroadCastBtn = (ImageView) findViewById(R.id.button_broadcast);
		tBroadCastBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					/*
					 * MediaPlayer player = new MediaPlayer();
					 * player.setDataSource(voice); player.prepare();
					 * player.start();
					 * 
					 * // 在这里显示和隐藏小人 ivNv.setVisibility(View.VISIBLE);
					 * player.setOnCompletionListener(new OnCompletionListener()
					 * {
					 * 
					 * @Override public void onCompletion(MediaPlayer mp) { //
					 * TODO Auto-generated method stub
					 * ivNv.setVisibility(View.GONE); }
					 * 
					 * });
					 */// 20141203不播放录音地址，直接播放文字信息
					/*
					 * 判断是否可以播放
					 * */
					
					if(mSpUtil.getIsBroadcast()){
						Synthesize();
					}
					else{
						Toast.makeText(getApplicationContext(), "语音播放功能已关闭!\n  请到设置中打开!", Toast.LENGTH_SHORT).show();
					}

					
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "没有获取到音频请重试！", 0)
							.show();
					e.printStackTrace();
				}
			}

		});
	}

	private void setWeatherForecast() {
		tvDate = (TextView) findViewById(R.id.forecast_date);
		tvStatus = (TextView) findViewById(R.id.forecast_weather_status);
		tvTemp = (TextView) findViewById(R.id.forecast_weather_temp);
		tvWindDirection = (TextView) findViewById(R.id.forecast_weather_wd);
		tvWind = (TextView)findViewById(R.id.forecast_weather_wind);
	}

	private void setWeatherActual() {
		tvActualTemp = (TextView) findViewById(R.id.currentTemp);
		tvActualAddress = (TextView) findViewById(R.id.currentLocation);
		tvActualTime = (TextView) findViewById(R.id.time);
		tvActualWet = (TextView) findViewById(R.id.wet);
		tvActualFall = (TextView) findViewById(R.id.fallwater);
		tvActualWindDirection = (TextView) findViewById(R.id.windDirection);
		tvActualWind = (TextView) findViewById(R.id.wind);
	}

	private void getWeatherActualData() {
		// 去接口获取实况信息
		try {
			Thread thread = new Thread() {
				@Override
				public void run() {
					WeatherHttpMethod whm = new WeatherHttpMethod(
							getApplicationContext());
					WeatherActual actual = whm.GetWeatherActual(
							mSpUtil.getAuthCode(),
							mApplication.getCurSimpleCity().cityCode);
					Message m = handler.obtainMessage(2, actual);
					handler.sendMessage(m);
				}
			};
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void checkVersion() {
		// 去接口获取版本号
		try {
			Thread thread = new Thread() {
				@Override
				public void run() {
					WeatherHttpMethod whm = new WeatherHttpMethod(
							getApplicationContext());
					String scode = whm.GetVersionCode(mSpUtil.getAuthCode());
					Message m = handler.obtainMessage(1, scode);
					handler.sendMessage(m);
				}
			};
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void setShareButtuon() {
		tShareBtn = (ImageView) findViewById(R.id.button_share);

		tShareBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.setType("text/plain");
				intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
				String shareString = mApplication.getCurSimpleCity().cityCode
						+ ":" + tvActualTime.getText() + "温度："
						+ tvActualTemp.getText() + "；降水："
						+ tvActualFall.getText() + "；风向："
						+ tvActualWindDirection.getText() + "；风力："
						+ tvActualWind.getText() + "【来自岳阳天气】";
				intent.putExtra(Intent.EXTRA_TEXT, shareString);
				startActivity(Intent.createChooser(intent, getTitle()));
			}

		});
	}

	private void setHourWeathers() {
		hourWeathers = (HorizontalListView) findViewById(R.id.hourWeathers);

		// 开一条子线程加载网络数据
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(0);
					WeatherHttpMethod http = new WeatherHttpMethod(
							ForecastActivity.this);
					weatherProfile = http.Getweatherforecasts(
							mSpUtil.getAuthCode(),
							mApplication.getCurSimpleCity().cityCode);
					Message msg = handler.obtainMessage(0, weatherProfile);
					handler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};

		try {
			// 开启线程
			new Thread(runnable).start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void setWarnings(List<Warning> warnings) {

		try {
			warningAdapter = new WarningAdapter(this, warnings);
			gvWarnings.setAdapter(warningAdapter);
			if (warnings.size() > 0) {
				gvWarnings.setVisibility(View.VISIBLE);
				gvWarnings.setNumColumns(warnings.size());
				LayoutParams params = new LayoutParams(warnings.size()
						* (160 + 5), LayoutParams.WRAP_CONTENT);
				gvWarnings.setColumnWidth(70);
				gvWarnings.setLayoutParams(params);
				gvWarnings.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> v, View view,
							int position, long id) {
						// TODO 传给下级页面信息
						try {
							Intent intent = new Intent(ForecastActivity.this,
									WarningListActivity.class);
							startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

				});
			}
		} catch (Exception e) {
		}
	}

	private void setHourWeathers(List<Map<String, Object>> list) {
		hourSimpleAdapter = new SimpleAdapter(this, list,
				R.layout.listview_item_hourweather, new String[] { "hour",
						"drawable", "temp" }, new int[] {
						R.id.hour_weather_hour, R.id.hour_weather_img,
						R.id.hour_weather_temp });
		// LayoutParams params = new LayoutParams(list.size() * (420 + 6),
		// LayoutParams.WRAP_CONTENT);
		// hourWeathers.setLayoutParams(params);
		// hourWeathers.setColumnWidth(210);
		// hourWeathers.setHorizontalSpacing(6);
		// hourWeathers.setStretchMode(GridView.NO_STRETCH);
		// hourWeathers.setNumColumns(list.size());
		hourWeathers.setAdapter(hourSimpleAdapter);
	}

	private void setDayWeathers(List<Map<String, Object>> list) {
		dayWeathers = (ListView) findViewById(R.id.dayWeathers);

		daySimpleAdapter = new SimpleAdapter(this, list,
				R.layout.listview_item_dayweather, new String[] { "week",
						"date", "img", "high", "low" }, new int[] {
						R.id.day_weather_week, R.id.day_weather_date,
						R.id.day_weather_img, R.id.day_weather_high,
						R.id.day_weather_low });
		dayWeathers.setAdapter(daySimpleAdapter);
		dayWeathers.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView adaperView, View arg1,
					int arg2, long arg3) {
				// int selectedPostion = adaperView.getSelectedItemPosition();
				Intent intent = new Intent(ForecastActivity.this,
						WeatherDetailActivity.class);
				startActivity(intent);
			}

		});
	}

	private void setForecast(WeatherProfile weatherProfile) {
		tvDate.setText("天气预报[" + weatherProfile.date + "]");
		tvStatus.setText("天气情况：" + weatherProfile.weatherStatus);
		tvTemp.setText("温度：" + weatherProfile.highTemp + " "
				+ weatherProfile.lowTemp);
		tvWindDirection.setText("风向：" + weatherProfile.windDirection);
		tvWind.setText("风力："+weatherProfile.wind);

		setWeatherStatus(weatherProfile);
	}

	private void setActual(WeatherActual actual) {
		tvActualTemp.setText(actual.temperature);
		tvActualAddress.setText(actual.address);
		tvActualTime.setText("[" + actual.postTime + "]");
		tvActualWet.setText(actual.humidity);
		tvActualFall.setText(actual.precipitation);
		tvActualWindDirection.setText(actual.windDirection);
		tvActualWind.setText(actual.wind);
	}

	private void setWeatherStatus(WeatherProfile weatherProfile) {

		mSpUtil.setWeatherStatus(weatherProfile.weatherStatus);

	}

	/**
	 * 获取天气列表数据
	 * */
	private void getDayWeathersData() {
		try {
			Thread thread = new Thread() {
				@Override
				public void run() {
					WeatherHttpMethod whm = new WeatherHttpMethod(
							getApplicationContext());
					List<WeatherDay> dayWeathers = whm.GetWeatherDays(
							mSpUtil.getAuthCode(),
							mApplication.getCurSimpleCity().cityCode);
					Message m = handler.obtainMessage(3, dayWeathers);
					handler.sendMessage(m);
				}
			};
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void setWarning() {
		getWarningData();
	}

	private void getWarningData() {
		try {
			Thread thread = new Thread() {
				@Override
				public void run() {
					WeatherHttpMethod whm = new WeatherHttpMethod(
							getApplicationContext());
					warnings = whm.GetWarning(mSpUtil.getAuthCode(),
							mApplication.getCurSimpleCity().cityCode);
					Message m = handler.obtainMessage(WhatIsGetWarnings,
							warnings);
					handler.sendMessage(m);
				}
			};
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void setCurrentTime() {
		currentTime = (TextView) findViewById(R.id.currentTime);
		String currentDate = TimeUtil.getSysDate();
		String currentNLDate = Lunar.getDay();
		String week = TimeUtil.getWeek();
		currentTime.setText(currentDate + " " + "农历" + currentNLDate + " "
				+ week);
	}

	/*
	 * 获取天气的图标
	 */
	private int GetWeatherIcon(String climate) {
		int result = 0;
		try {
			result = mApplication.getWidgetWeatherIcon(climate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.forecast, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCityComplite() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNetChange() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			mTts.stopSpeaking();
			// 退出时释放连接
			mTts.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void Synthesize() {
		try {
			// 改为播放音频文件
			String voice = mApplication.GetCurAudioPath();// "http://222.242.199.5:3888/voice/voice.wav";
			if (voice == null || voice == "") {
				Toast.makeText(getApplicationContext(), "没有获取到音频请重试！", 0)
						.show();
				voice = "http://222.242.199.5:3888/voice/voice.wav";// 临时测试
			}
			if (voice == null || voice == "") {
				voice = "当前没有获取到天气信息，请重试";
			}
			// 设置参数
			setParam();
			int code = mTts.startSpeaking(voice, mTtsListener);
			if (code != ErrorCode.SUCCESS) {
				if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
					// 未安装则跳转到提示安装页面
					IntallXunFei();
				} else {
					Toast.makeText(getApplicationContext(),
							"语音合成失败,错误码: " + code, 0).show();
				}
			}
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "音频播放错误，请重试！", 0).show();
			e.printStackTrace();
		}
	}

	/**
	 * 初期化监听。
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
			// Log.d(TAG, "InitListener init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
				Toast.makeText(getApplicationContext(), "初始化失败,错误码：" + code, 0)
						.show();
			}
		}
	};

	/**
	 * 合成回调监听。
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener() {
		@Override
		public void onSpeakBegin() {
			ivNv.setVisibility(View.VISIBLE);
		}

		@Override
		public void onSpeakPaused() {

		}

		@Override
		public void onSpeakResumed() {

		}

		@Override
		public void onBufferProgress(int percent, int beginPos, int endPos,
				String info) {

		}

		@Override
		public void onSpeakProgress(int percent, int beginPos, int endPos) {

		}

		@Override
		public void onCompleted(SpeechError error) {
			ivNv.setVisibility(View.INVISIBLE);
			if (error != null) {
				//Toast.makeText(getApplicationContext(),
				//		error.getPlainDescription(true), 0).show();
			}
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

		}
	};

	/**
	 * 参数设置
	 * 
	 * @param param
	 * @return
	 */
	private void setParam() {

		// 设置合成
		if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE,
					SpeechConstant.TYPE_CLOUD);
			// 设置发音人
			mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
		} else {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE,
					SpeechConstant.TYPE_LOCAL);
			// 设置发音人 voicer为空默认通过语音+界面指定发音人。
			mTts.setParameter(SpeechConstant.VOICE_NAME, "");
		}
		
		mTts.setParameter(SpeechConstant.LANGUAGE, "zh_cn");

		// 设置语速
		mTts.setParameter(SpeechConstant.SPEED, "50");

		// 设置音调
		mTts.setParameter(SpeechConstant.PITCH, "50");

		// 设置音量
		mTts.setParameter(SpeechConstant.VOLUME, "50");

		// 设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
	}

	/*
	 * 询问安装讯飞*/
	protected void IntallXunFei() {
		/*
		try{
			AlertDialog.Builder builder = new Builder(ForecastActivity.this);
			builder.setMessage("语音播放需要下载讯飞语音进行支持，是否下载？");
			builder.setTitle("提示");
			builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
			
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					String url = SpeechUtility.getUtility().getComponentUrl();
					String assetsApk="SpeechService.apk";
					processInstall(ForecastActivity.this, url,assetsApk);
				}});
			
			builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}});
			
			builder.create().show();
		}catch(Exception e){e.printStackTrace();}
		*///20141204暂时是云播放，所以本地检测安装的就不要了
	}
	
	/**
	 * 如果服务组件没有安装打开语音服务组件下载页面，进行下载后安装。
	 */
	private boolean processInstall(Context context ,String url,String assetsApk){
		//直接下载方式
		Uri uri = Uri.parse(url);
		Intent it = new Intent(Intent.ACTION_VIEW, uri);
		context.startActivity(it);
		return true;		
	}
	
}
